﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ReportFlat.Common;
using ReportFlat.DataAccess;
using System.Collections;


namespace ReportFlat.Web.server.customer
{
    /// <summary>
    /// Supplier 的摘要说明
    /// </summary>
    public class Contract : BaseHandler
    {
        /// <summary>
        /// 保存
        /// </summary>
        [UseDB(Transaction = true)]
        public void Save()
        {
            c_contract obj = ToPo<c_contract>();
            //去掉时间部分
            obj.FDeadlineBeg = obj.FDeadlineBeg.Date;
            obj.FDeadlineEnd = obj.FDeadlineEnd.Date;
            if (obj.FID == 0)
            {
                obj.FCreateDate = DateTime.Now;
                dao.Save(obj);
            }
            else
            {
                dao.Update(obj);
            }
            //更新项目是否签订合同
            //改变项目的时候，以前的合同应该更新一遍
            c_project project = dao.Get<c_project>(obj.FProjectID);
            if (project != null && project.FIsHasContract!="是")
            {
                project.FIsHasContract = "是";
                dao.Save(project);
            }
            jsonResult = JSONHelper.SuccessJson;
        }

        /// <summary>
        /// 删除
        /// </summary>
        [UseDB(Transaction = true)]
        public void Delete()
        {
            int contractID = Convert.ToInt32(Request["FID"]);
            //更新项目是否获得资金
            c_contract contract = dao.Get<c_contract>(contractID);
            if (contract != null)
            {
                dao.Delete(contract);
                dao.ExcuteByHSql("delete from c_contract_income where FContractID=" + contractID);
                dao.ExcuteByHSql("delete from c_contract_expend where FContractID=" + contractID);

                int count = dao.GetRowCount("from c_contract where FProjectID=" + contract.FProjectID);
                if (count == 0)
                {
                    c_project project = dao.Get<c_project>(contract.FProjectID);
                    if (project != null && project.FIsHasContract != "否")
                    {
                        project.FIsBankroll = "否";
                        dao.Save(project);
                    }
                }
            }
            jsonResult = JSONHelper.SuccessJson;
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        [UseDB]
        public void GetList()
        {
            int start = int.Parse(Request.Params["start"].ToString());
            int limit = int.Parse(Request.Params["limit"].ToString());
            string sWhere = Request.Params["where"].ToString();
            string PayedAll = JSONHelper.GetString(Request["oWhere"], "PayedAll");
            string IsBankroll = JSONHelper.GetString(Request["oWhere"], "IsBankroll");
            int rowCount;
            //加权限控制
            //roleid=12是咨询部
            if (!GMLogin.isAdminUser() && !GMLogin.isRole(12))
            {
                sWhere = sWhere.and("Customer.FUserID=" + GMLogin.UserID);
            }
            if (!string.IsNullOrEmpty(PayedAll))
            {
                if (PayedAll == "否")
                {
                    sWhere = sWhere.and("FActAmount <= FPayedAmount");
                }
                else if (PayedAll == "是")
                {
                    sWhere = sWhere.and("FActAmount > FPayedAmount");
                }
            }
            if (!string.IsNullOrEmpty(IsBankroll))
            {
                if (IsBankroll == "否")
                {
                    sWhere = sWhere.and("(FAmount * FCustCommission / 100)<=0");
                }
                else if (IsBankroll == "是")
                {
                    sWhere = sWhere.and("(FAmount * FCustCommission / 100)>0");
                }
            }
            IList<c_contract> list = dao.GetList<c_contract>(out rowCount, sWhere, "FDeadlineBeg desc,FNo desc", start, limit);
            jsonResult = JSONHelper.ToSucJson((IList)list, rowCount);
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        [UseDB]
        public void GetListByProject()
        {
            IList<c_contract> list = dao.GetList<c_contract>("FProjectID=" + Request["FProjectID"], "", 0, 20);
            jsonResult = JSONHelper.ToSucJson("data",list);
        }

        /// <summary>
        /// 获取下拉列表
        /// </summary>
        [UseDB]
        public void GetOptions()
        {
            IList<c_contract> list = dao.GetList<c_contract>();
            jsonResult = JSONHelper.ToSucJson("options", (IList)list);
        }


        /// <summary>
        /// 下载Excel
        /// </summary>
        [UseDB]
        public void ExportExcel()
        {
            string sWhere = this.context.Server.UrlDecode(Request.Params["where"].ToString());
            int rowCount;
            IList<c_contract> list = dao.GetList<c_contract>(out rowCount, sWhere, "FDeadlineBeg desc,FNo desc", 0, 10000);
            CreateExcel(list);
        }

        private void CreateExcel(IList<c_contract> list)
        {
            String fileName = "合同" + DateTime.Now.ToString("yyyyMMdd") + ".csv";
            String[] Columns = { "合同编号", "公司名称", "项目申报名称",
                                 "申报资金种类","跟单员", "材料收集情况", "资金年限","申报等级","合同点数", "业务提成",
                                 "省份", "城市", "付款方式",
                                 "应得咨询费总额", "实际获咨询费总额", "已付金额","咨询师", "更换咨询师",
                                 "合同完成时间", "公司规定完成时间", "备注","收入信息", "费用信息"};
            HttpResponse resp;
            resp = this.Response;
            resp.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
            resp.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
            string colHeaders = "", ls_item = "";

            int i = 0;
            int cl = Columns.Length;

            //取得数据表各列标题，各标题之间以t分割，最后一个列标题后加回车符 
            for (i = 0; i < cl; i++)
            {
                if (i == (cl - 1))//最后一列，加n
                {
                    colHeaders += Columns[i] + "\r\n";
                }
                else
                {
                    colHeaders += Columns[i] + ",";
                }

            }
            resp.Write(colHeaders);
            //向HTTP输出流中写入取得的数据信息 
            //String[] Columns = { "合同编号", "公司名称", "项目申报名称",
            //                     "申报资金种类","跟单员", "材料收集情况", "资金年限","申报等级","合同点数", "业务提成",
            //                     "省份", "城市", "付款方式",
            //                     "总金额", "实际获得奖励金额", "已付金额","咨询师", "更换咨询师",
            //                     "合同完成时间", "公司规定完成时间", "备注","收入信息", "费用信息"};
            //逐行处理数据   
            foreach (c_contract row in list)
            {
                ls_item += FormatHtmlStr(row.FNo) + ",";
                ls_item += FormatHtmlStr(row.CustomerName) + ",";
                ls_item += FormatHtmlStr(row.FProjectName) + ",";
                ls_item += FormatHtmlStr(row.FBankrollType) + ",";
                ls_item += FormatHtmlStr(row.UserName) + ",";
                ls_item += FormatHtmlStr(row.Collections) + ",";
                ls_item += FormatHtmlStr(row.FDeadline) + ",";
                ls_item += FormatHtmlStr(row.FGrade) + ",";
                ls_item += FormatHtmlStr(row.FCustCommission) + ",";
                ls_item += FormatHtmlStr(row.FCommission) + ",";
                ls_item += FormatHtmlStr(row.Provice) + ",";
                ls_item += FormatHtmlStr(row.City) + ",";
                ls_item += FormatHtmlStr(row.FPayWay) + ",";
                ls_item += FormatHtmlStr(row.FAmount) + ",";
                ls_item += FormatHtmlStr(row.FActAmount) + ",";
                ls_item += FormatHtmlStr(row.FPayedAmount) + ",";
                ls_item += FormatHtmlStr(row.FCounselor) + ",";
                ls_item += FormatHtmlStr(row.FSecCounselor) + ",";
                ls_item += row.FCompletedDate.ToString("yyyy-MM-dd") + ",";
                ls_item += row.FToCompletedDate.ToString("yyyy-MM-dd") + ",";
                ls_item += FormatHtmlStr(row.FNote) + ",";
                ls_item += FormatHtmlStr(row.FIncomeInfo) + ",";
                ls_item += FormatHtmlStr(row.FExpendInfo) + "\r\n";
                resp.Write(ls_item);
                ls_item = "";
            }
            //resp.End();
        }

        private string FormatHtmlStr(object s)
        {
            if (s == null)
            {
                return "";
            }
            string result = s.ToString();
            result = result.Replace("<font color=blue>", "");
            result = result.Replace("</font>", "");
            result = result.Replace("</font>", "");
            result = result.Replace(",", ";");
            result = result.Replace("，", ";");
            result = result.Replace("<br>", "     ");
            result = result.Replace("\r\n", "     ");
            result = result.Replace("\n", "     ");
            return result.ToString();
        }
    }
}